import React, { useEffect, useRef, useState, useLayoutEffect } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { CenterPage, CenterBottom } from '../centerPage/style';
import { ModuleTitle } from '../../style/globalStyledSet';
import { BorderBox12, BorderBox13 } from '@jiaminghi/data-view-react';

import Map from '../centerPage/charts/Map';
import { connect } from 'dva';
import {
  RightPage,
  RightTopBox,
  RightCenterBox,
  RightBottomBox,
} from './style';
import * as dashboardApi from '../../services/api'; // 根据你的实际路径调整

//1-图表配置工具函数
//1-1对比图
const COMPARE_CHART_CONFIG = (data) => ({
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      let resultSpilt = [
        `<div style="font-weight: bold; margin: 4px 0px;">---------------------------</div>`,
      ];
      params.forEach((param) => {
        if (param.seriesName.includes('项目文档交付率')) {
          result.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%</br>
                  已交付: ${
                    data.docDelivery[param.dataIndex].deliveredQuantity
                  }</br>
                  总数: ${data.docDelivery[param.dataIndex].projectTotal}</br>
                </div>
              `);
        }
        if (param.seriesName.includes('工程文件交付率')) {
          resultSpilt.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%</br>
                  已交付: ${
                    data.fileDelivery[param.dataIndex].deliveredQuantity
                  }</br>
                  总数: ${data.fileDelivery[param.dataIndex].projectTotal}</br>
                </div>
              `);
        }

        // const seriesName = param.seriesName;
        // const dataIndex = param.dataIndex;
        // const dataSet =
        //   seriesName === '项目文档交付率'
        //     ? data.docDelivery[dataIndex]
        //     : data.fileDelivery[dataIndex];
        // result += `${seriesName}: ${(param.value * 100).toFixed(2)}%<br/>`;
        // if (seriesName === '项目文档交付率') {
        //   result += `已交付: ${dataSet.deliveredQuantity}份<br/>总需求: ${dataSet.projectTotal}份<br/>`;
        // } else {
        //   result += `已交付: ${dataSet.deliveredQuantity}个<br/>总数: ${dataSet.projectTotal}个<br/>`;
        // }
      });

      if (resultSpilt.length > 1) {
        return result.join('') + resultSpilt.join('');
      } else {
        return result.join('');
      }
    },
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    data: ['项目文档交付率', '工程文件交付率'],
    textStyle: {
      color: '#bad9ed',
    },
  },
  grid: {
    top: '13%',
    left: '5%',
    right: '10%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    show: false,
  },
  yAxis: {
    type: 'category',
    data: data.departments,
    inverse: true,
    axisLine: { show: false },
    splitLine: { show: false },
    axisTick: { show: false },
    axisLabel: {
      interval: 0,
      // color: '#bad9ed',
      // interval: 0,
      // // rotate: 30,
      color: '#fff',
      margin: 10,
      rich: {
        lg: {
          backgroundColor: '#339911',
          color: '#fff',
          borderRadius: 15,
          // padding: 5,
          align: 'center',
          width: 15,
          height: 15,
          // height: 205,
          // lineHeight: 250,
        },
      },
    },
  },
  series: [
    {
      name: '项目文档交付率',
      type: 'bar',
      data: data.docDelivery.map((item) => item.rate),
      yAxisIndex: 0,
      barCategoryGap: 0,
      barWidth: 10,
      itemStyle: {
        color: '#1089E7', // 直接使用color属性
        barBorderRadius: 20, // 直接设置borderRadius
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: (params) => {
            // params 包含完整数据信息
            return `${(params.value * 100).toFixed(2)}%`;
          },
          color: 'rgba(224, 224, 224, 0.9)',
        },
      },
    },
    {
      name: '工程文件交付率',
      type: 'bar',
      data: data.fileDelivery.map((item) => item.rate),
      yAxisIndex: 0,
      barCategoryGap: 0,
      barWidth: 10,
      itemStyle: {
        color: '#56D0E3',
        barBorderRadius: 20,
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: (params) => {
            // params 包含完整数据信息
            return `${(params.value * 100).toFixed(2)}%`;
          },
          color: 'rgba(224, 224, 224, 0.9)',
          textStyle: {
            // 新增 textStyle 设置字体大小
            fontSize: 12, // 设置字体大小（单位：px）
          },
        },
      },
    },
  ],
});
//1-2趋势图
const colors = [
  '#0184d5',
  '#FF9F43',
  '#27AE60',
  '#E74C3C',
  '#9B59B6',
  '#3498DB',
  '#F1C40F',
  '#1ABC9C',
  '#D35400',
  '#34495E',
];
var TREND_CHART_CONFIG = (data) => ({
  // color: colors,
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    textStyle: {
      fontSize: 14,
    },
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      let resultSpilt = [
        `<div style="font-weight: bold; margin: 4px 0px;">---------------------------</div>`,
      ];
      params.forEach((param) => {
        if (param.seriesName.includes('项目文档交付率')) {
          result.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%
                </div>
              `);
        }
        if (param.seriesName.includes('工程文件交付率')) {
          resultSpilt.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%
                </div>
              `);
        }
      });
      if (resultSpilt.length > 1) {
        return result.join('') + resultSpilt.join('');
      } else {
        return result.join('');
      }
    },
  },
  legend: {
    type: 'scroll',
    orient: 'horizontal',
    bottom: '5%',
    data: [
      ...data.departments.map((dept) => dept + '-项目文档交付率'),
      ...data.departments.map((dept) => dept + '-工程文件交付率'),
    ],
    textStyle: {
      color: '#FFFFFF', // 字体颜色（白色）
    },
    pageTextStyle: {
      // 分页按钮文字样式
      color: '#CCCCCC',
    },
    itemHeight: 14,
  },
  grid: {
    left: '3%',
    right: '3%',
    bottom: '20%',
    top: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: data.months,
    axisLabel: {
      color: '#bad9ed',
      interval: 0,
      rotate: 30,
    },
  },
  yAxis: {
    type: 'value',
    min: 0,
    max: 1,
    axisLabel: {
      color: '#bad9ed',
      formatter: function (value) {
        // 更安全的百分比格式化
        return Math.round(value * 100 * 100) / 100 + '%'; // 保留两位小数
      },
    },
    // 修改y轴分割线的颜色
    splitLine: {
      lineStyle: {
        color: '#012f4a',
      },
    },
  },
  series: [
    ...data.departments.map((dept, index) => ({
      name: `${dept}-项目文档交付率`,
      type: 'line',
      itemStyle: {
        color: colors[index % colors.length],
      }, // 循环取色
      lineStyle: {
        color: colors[index % colors.length], // 设置线条颜色
        width: 2,
      },
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[index % colors.length] + '80' },
          { offset: 1, color: colors[index % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.docDelivery.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.rate : 0;
      }),
    })),
    ...data.departments.map((dept, index) => ({
      name: `${dept}-工程文件交付率`,
      type: 'line',
      smooth: true,
      itemStyle: {
        color: colors[(index + 2) % colors.length],
      },
      lineStyle: {
        type: 'dashed',
        color: colors[(index + 2) % colors.length], // 设置虚线颜色
        width: 2,
      },
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[(index + 2) % colors.length] + '80' },
          { offset: 1, color: colors[(index + 2) % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.fileDelivery.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.rate : 0;
      }),
    })),
  ],
});

//2-数据处理函数
//2-1趋势图
const processChartData = (rawData) => {
  const uniqueDepts = [...new Set(rawData.map((item) => item.departmentName))];
  const uniqueMonths = [...new Set(rawData.map((item) => item.month))];

  return {
    departments: uniqueDepts,
    months: uniqueMonths,
    docDelivery: rawData.filter((r) => r.type === '项目文档交付率'),
    fileDelivery: rawData.filter((r) => r.type === '工程文件交付率'),
  };
};

//主体
const ProjectDelivery = () => {
  const trendChartRef = useRef(null);
  const compareChartRef = useRef(null);
  const [compareData, setCompareData] = useState(null);
  const [trendData, setTrendData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  //创建数据获取函数
  const fetchData = async () => {
    try {
      setLoading(true);

      // 并行请求数据
      const [compareResponse, trendResponse] = await Promise.all([
        dashboardApi.getProjectDeliveryByBuAsync(),
        dashboardApi.getProjectDeliveryByTrendAsync(),
      ]);
      setCompareData(processChartData(compareResponse.data.content));
      setTrendData(processChartData(trendResponse.data.content));
    } catch (err) {
      setError(err.message || '获取数据失败');
      console.error('API调用错误:', err);
    } finally {
      setLoading(false);
    }
  };

  //在 useEffect 中调用数据获取
  useEffect(() => {
    fetchData();
    return () => {
      [trendChartRef, compareChartRef].forEach((ref) => {
        if (ref.current) echarts.dispose(ref.current);
      });
    };
  }, []);

  useLayoutEffect(() => {
    if (!compareData || !compareChartRef.current) {
      console.log('对比图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('对比图表开始初始化');

    // 2. 对比图
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption(COMPARE_CHART_CONFIG(compareData));
    window.addEventListener('resize', () => compareChart.resize());

    return () => {
      compareChart.dispose(); // 清理对比图实例
    };
  }, [compareData]); // 依赖 data 属性变化

  useLayoutEffect(() => {
    if (!trendData || !trendChartRef.current) {
      console.log('趋势图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('趋势图表开始初始化');
    // 1. 趋势图
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption(TREND_CHART_CONFIG(trendData));
    window.addEventListener('resize', () => trendChart.resize());

    return () => {
      trendChart.dispose(); // 清理趋势图实例
    };
  }, [trendData]); // 依赖 data 属性变化

  return (
    <RightPage>
      <br />
      <ModuleTitle>
        <i className="iconfont">&#xe78f;</i>
        <span>项目交付</span>
      </ModuleTitle>
      <BorderBox12 style={{ height: '5rem' }}>
        <ModuleTitle>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <span>项目文档与工程文件交付率 - 事业部对比</span>
        </ModuleTitle>
        <div
          ref={compareChartRef}
          style={{
            width: '100%',
            height: '4rem',
          }}
        ></div>
      </BorderBox12>
      <BorderBox13 style={{ height: '6.25rem', marginTop: '0.4rem' }}>
        <br />
        <div className="right-top">
          <ModuleTitle>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span>项目文档与工程文件交付率趋势</span>
          </ModuleTitle>
          <div className="right-top-content">
            <div
              ref={trendChartRef}
              style={{
                width: '100%',
                height: '5rem',
              }}
            ></div>
          </div>
        </div>
      </BorderBox13>

      <RightBottomBox></RightBottomBox>
    </RightPage>
  );
};

export default ProjectDelivery;
